#!/bin/bash -ex

function find_kdir() {
    local kdirs=(/usr/lib/modules/*/build/Makefile /usr/src/kernels/*/Makefile)
    local kdir=""

    for f in "${kdirs[@]}"; do
        if [ -f "$f" ]; then
            kdir=$f
            break
        fi
    done

    if [ -z "$kdir" ]; then
        printf '==> Unable to find kernel headers to build modules for tests\n' >&2
        exit 1
    fi

    kdir=${kdir%/Makefile}

    echo $kdir
}

if [ -f configure ]; then
    make distclean
fi

rm -rf build
mkdir build
cd build

kdir=$(find_kdir)
IFS=/ read _ _ _ kver _ <<<"$kdir"

../autogen.sh c --disable-python
make -j
make check KDIR="$kdir" KVER="$kver"
make install
